package cn.trip.auth.controller;


import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.*;
import cn.trip.auth.service.ItripUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Api(value = "register|用户注册的控制器")
@Controller
@RequestMapping("/api")
public class RegisteredController {
    String uuid = UUID.randomUUID().toString();//产生uuid
    String num = "";
    String uuid2 = UUID.randomUUID().toString();//新的uuid
    String nums = "";
    String order = "";
    Dto dto = null;
    @Autowired
    private Md5Util md5Util;
    @Resource(name = "itripUserService")
    private ItripUserService itripUserService;

//    @RequestMapping(value = "/register", method = RequestMethod.POST)
//    public String login() {
//        return "/register.jsp";
//    }

    @RequestMapping(value = "/doregister", method = RequestMethod.POST)
    @ApiOperation(value = "邮箱注册必须传邮箱信息", notes = "要输入邮箱号码，密码，激活码,用户名", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userCode", value = "账号", required = true),
            @ApiImplicitParam(paramType = "query", name = "userPassword", value = "密码", required = true),
            @ApiImplicitParam(paramType = "query", name = "userName", value = "用户名", required = true)
    })
    @ResponseBody
    public Dto tomailregister(@RequestBody Map<String, String> usermap) {
        ItripUser user = new ItripUser();
        user.setUserCode(usermap.get("userCode"));
        user.setUserName(usermap.get("userName"));
        user.setUserPassword(md5Util.encode(usermap.get("userPassword")));
        user.setActivated(0);  //刚注册默认是没有激活状态
        //注册用户
        if (itripUserService.findUserCode(user)) {
            dto = new Dto();
            dto.setSuccess("true");
            dto.setMsg("邮箱注册成功");
            dto.setData(user);
            dto.setErrorCode("0");
            itripUserService.insert(user);
            ItripUser itripUser = new ItripUser();
            user.setUserCode(usermap.get("userCode"));
            MailUtil.sendAccountActivateEmail(user, uuid);
            try {
                num = GenerateLinkUtils.generateActivateLink(user, uuid);
                itripUserService.addVerificationCode("order:" + usermap.get("userCode"), num);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("该邮箱已被注册");
        }
        return dto;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "user", value = "账号"),
            @ApiImplicitParam(paramType = "query", name = "code", value = "激活码"),

    })
    @ResponseBody
    @RequestMapping("/activate")
    public Dto mileactivation(@RequestParam(name = "code") String code, @RequestParam(name = "user") String user) {
        ItripUser itripUser = new ItripUser();
        itripUser.setUserCode(user);
        //查看是否注册成功，为实体类User的id赋值
        if (!(itripUserService.findUserCode(itripUser))) {
            ItripUser fingUser = itripUserService.selectUserid(user);
            itripUser.setId(fingUser.getId());
            //注册成功后，发送账户激码
            long idInt = itripUser.getId();
            String userName = fingUser.getUserCode();
            //根据用户id查找用户
            ItripUser itripUser1 = itripUserService.findUserById(idInt);
            if (fingUser.getActivated() == 0) {
                //验证无误，状态更改为1，即激活
                if (itripUserService.getVerificationCode("order:" + userName).equals(code)) {
                    System.out.println((itripUserService.getVerificationCode(num)));
                    //修改状态
                    int activated = 1;
                    itripUserService.updateActivated(activated, idInt);
                    itripUser1.setActivated(1);
                    dto = new Dto();
                    dto.setSuccess("true");
                    dto.setMsg("恭喜，账号激活成功");
                    dto.setData(itripUser1);
                    dto.setErrorCode("0");
                } else {
                    dto = new Dto();
                    dto.setSuccess("false");
                    dto.setMsg("账号激活失败");
                    dto.setData(itripUser1);
                }
            } else {
                dto = new Dto();
                dto.setSuccess("false");
                dto.setMsg("账号已激活，请去登陆");
            }
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("账号不存在，请先去注册");

        }
        return dto;
    }


    @RequestMapping(value = "/registerbyphone", method = RequestMethod.POST)
    @ApiOperation(value = "手机注册必须传手机信息", notes = "要输入手机号码，密码，激活码,用户名")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userCode", value = "账号"),
            @ApiImplicitParam(paramType = "query", name = "userPassword", value = "密码"),

            @ApiImplicitParam(paramType = "query", name = "userName", value = "用户名")
    })
    @ResponseBody
    public Dto tophoneregister(@RequestBody Map<String, String> usermap) {


        ItripUser user = new ItripUser();
        user.setUserCode(usermap.get("userCode"));
        user.setUserName(usermap.get("userName"));
        user.setUserPassword(md5Util.encode(usermap.get("userPassword")));
        user.setActivated(0);  //刚注册默认是没有激活状态

        //注册用户
        if (itripUserService.findUserCode(user)) {
            dto = new Dto();
            dto.setSuccess("true");
            dto.setMsg("手机注册成功");
            dto.setData(user);
            dto.setErrorCode("0");
            itripUserService.insert(user);
            user.setUserCode(usermap.get("userCode"));
            String host = "http://yzx.market.alicloudapi.com";
            String path = "/yzx/sendSms";
            String method = "POST";
            String appcode = "ecbe9ec015ff4aacbfa08d89d188d704";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            Map<String, String> querys = new HashMap<String, String>();
            querys.put("mobile", usermap.get("userCode"));
            nums = GenerateLinkUtils.generateActivateLink(user, uuid2);
            order = nums.substring(0, 4);
            //把code放到redis缓存中
            querys.put("param", "code:" + order);
            itripUserService.addVerificationCode("order:" + usermap.get("userCode"), order);
            querys.put("tpl_id", "TP1710262");
            Map<String, String> bodys = new HashMap<String, String>();
            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                PhoneUtil.doPost(host, path, method, headers, querys, bodys);
                //获取response的body
                //System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("该手机已被注册");

        }
        return dto;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "user", value = "账号"),
            @ApiImplicitParam(paramType = "query", name = "code", value = "激活码"),

    })
    @ResponseBody
    @RequestMapping("/validatephone")
    public Dto activation(@RequestParam(name = "code") String code, @RequestParam(name = "user") String user) {
        ItripUser itripUser = new ItripUser();
        itripUser.setUserCode(user);
        //查看是否注册成功，为实体类User的id赋值
        if (!(itripUserService.findUserCode(itripUser))) {
            ItripUser fingUser = itripUserService.selectUserid(user);
            itripUser.setId(fingUser.getId());
            String userName = fingUser.getUserCode();
            //注册成功后，发送账户激码

            long idInt = itripUser.getId();
            //根据用户id查找用户
            ItripUser itripUser1 = itripUserService.findUserById(idInt);
            if (fingUser.getActivated() == 0) {
                //验证无误，状态更改为1，即激活
                if (itripUserService.getVerificationCode("order:" + userName).equals(code)) {
                    //修改状态
                    int activated = 1;
                    itripUserService.updateActivated(activated, idInt);
                    itripUser1.setActivated(1);
                    dto = new Dto();
                    dto.setSuccess("true");
                    dto.setMsg("恭喜，账号激活成功");
                    dto.setData(itripUser1);
                    dto.setErrorCode("0");
                } else {
                    dto = new Dto();
                    dto.setSuccess("false");
                    dto.setMsg("账号激活失败");
                    dto.setData(itripUser1);
                }
            } else {
                dto = new Dto();
                dto.setSuccess("false");
                dto.setMsg("账号已激活，请去登陆");
            }

        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("账号不存在，请先去注册");

        }
        return dto;
    }

    @RequestMapping(value = "/ckusr", method = RequestMethod.GET)
    @ResponseBody
    public Dto ckuser(@RequestParam(name = "name") String name) {
        ItripUser user = new ItripUser();
        Dto dto = new Dto();
        user.setUserCode(name);
        if (itripUserService.findUserCode(user)) {
            dto.setSuccess("true");
            dto.setMsg("可以注册");
            dto.setErrorCode("0");
        } else {
            dto = new Dto();
            dto.setSuccess("false");
            dto.setMsg("该邮箱已被注册");
        }
        return dto;
    }
}





